package com.feicheng.common.util;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class StringGenerator {

    private static final int DEFAULT_LENGTH = 10;
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final StringBuilder builder = new StringBuilder();

    public static String generate() {
        return generate(DEFAULT_LENGTH);
    }

    public static String generate(int length) {
        return RandomStringUtils.random(length, CHARACTERS.toCharArray());
    }

    public static String getID(String title) {
        LocalDateTime now = LocalDateTime.now();
        if (null == title) {
            title = "ID";
        }
        StringBuilder sb = new StringBuilder(title);
        sb.append(now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")))
                .append(generate(32 - 14 - title.length()));
        return sb.toString();
    }

    public static String getID() {
        return getID(null);
    }

    public static String trimLeft(String target, String p) {
        return target.replaceAll("^("+p+"+)", "");
    }

    public static String trimRight(String target, String p) {
        return target.replaceAll(p+"*$", "");
    }


    public static String md5(String target) {
        return DigestUtils.appendMd5DigestAsHex(target.getBytes(), new StringBuilder()).toString();
    }

    public static String getSalt(int length) {
        return generate(length);
    }

    public static String eCodePassword(String password, String salt) {
        return md5(password+salt);
    }

    public static String addRight(String target, String p, int length) {
        for (int i = 0; i < length; i++) {
            target += p;
        }
        return target;
    }

    public static String addLeft(String target, String p, int length) {
        for (int i = 0; i < length; i++) {
            target  = p + target;
        }
        return target;
    }

    public static void main(String[] args) {
        System.out.println(eCodePassword("123456", "abcde"));
    }

}
